<?php

namespace App\Http\Controllers\Api;

use App\Constants\MiniProgramConstant;
use App\Constants\TagConstant;
use App\Http\Requests\Api\IdMustRequest;
use App\Http\Resources\ArticleResource;
use App\Models\Article;
use App\Models\Tag;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function hot()
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $hot = Article::where(['type' => 1, 'is_hot' => 1])
            ->when($switch != 1, function ($q) {
               return $q->where('mini_type', $this->getMiniType());
            })
            ->with(['publisher', 'comments', 'hot_news_tag'])
            ->orderBy('is_top', 'desc')
            ->orderBy('created_at', 'desc')
            ->limit('5')
            ->get();
        $hot = ArticleResource::collection($hot);

        $new = Article::where(['type' => 2, 'is_hot' => 1])
            ->when($switch != 1, function ($q) {
                return $q->where('mini_type', $this->getMiniType());
            })
            ->orderBy('is_top', 'desc')
            ->orderBy('created_at', 'desc')
            ->limit('5')
            ->get();
        $new = ArticleResource::collection($new);

        return $this->success('success', compact('hot', 'new'));
    }

    public function list(Request $request)
    {
        $type = $request->input('type', 1);
        $tagId = $request->input('tag_id');

        $with = array_merge(['publisher', 'comments'], $type == 1 ? ['hot_news_tag'] : ['tag']);

        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $list = Article::where(['type' => $type])
            ->when($switch != 1, function ($q) {
                return $q->where('mini_type', $this->getMiniType());
            })
            ->when($tagId, function ($q) use($tagId) {
                return $q->where('tag_id', '=', $tagId);
            })
            ->with($with)
            ->orderBy('is_top', 'desc')
            ->orderBy('id', 'desc')
            ->paginate();

        return $this->success('success', ArticleResource::collection($list));
    }

    public function detail(IdMustRequest $request)
    {
        $id = $request->id;

        $memberId = auth('api')->user()->id ?? 0;

        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $info = Article::with(['publisher', 'all_comments' => function($q) use($memberId) {
            if (!$memberId) {
                $q->where('status', '=', 1);
            } else {
                $q->whereRaw('IF(member_id = ?, status < ?, status = ?)', [$memberId, 2, 1]);
            }
        }])->when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($id);

        if (!$info)
            return $this->error('文章不存在');

        $info->increment('pageviews');

        $info->load($info->type == 1 ? 'hot_news_tag' : 'tag');

        return $this->success('success', new ArticleResource($info));
    }

    public function favor(IdMustRequest $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $article = Article::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($request->id);
        $user = auth('api')->user();
        if ($user->favoriteArticles()->find($request->id) || !$article) {
            return $this->success('success');
        }

        $user->favoriteArticles()->attach($article);
        $article->increment('fav_count');
        if ($member = $article->publisher->member)
            $member->increment('favs_count');

        return $this->success('success');
    }

    public function disfavor(IdMustRequest $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $article = Article::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($request->id);
        $user = auth('api')->user();
        if (!$user->favoriteArticles()->find($request->id) || !$article) {
            return $this->success('success');
        }

        $user->favoriteArticles()->detach($article);
        $article->decrement('fav_count');
        if ($member = $article->publisher->member)
            $member->decrement('favs_count');

        return $this->success('success');
    }

    public function relay(IdMustRequest $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $article = Article::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($request->id);
        if (!$article) {
            return $this->success('success');
        }

        $article->increment('relay_count');
        if (auth('api')->check())
            auth('api')->user()->increment('relay_count');

        return $this->success('success');
    }

    public function delete(Request $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $id = $request->input('id');
        $article = Article::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($id);
        $article->delete();
        $article->comments()->delete();
        if ($article->trashed()) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

    public function setHot(Request $request)
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $id = $request->input('id');
        $is_hot = $request->input('is_hot', 1);
        $article = Article::when($switch != 1, function ($q) {
            return $q->where('mini_type', $this->getMiniType());
        })->find($id);
        $article->is_hot = $is_hot;
        if ($article->save()) {
            return $this->success('操作成功');
        } else {
            return $this->error('操作失败');
        }
    }

    public function tags()
    {
        $switch = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP, MiniProgramConstant::ALL_ARTICLE_SWITCH) ?? 0;

        $list = Tag::where(['type' => TagConstant::TAG_BY_ARTICLE])
            ->when($switch != 1, function ($q) {
                return $q->where('mini_type', $this->getMiniType());
            })
            ->where('status', '=', true)
            ->orderByDesc('sort')
            ->select('name', 'id')
            ->get();

        return $this->_success(compact('list'));
    }
}
